"""
MongoDB 客户端封装
"""
from __future__ import annotations

from threading import Lock
from typing import Optional

from pymongo import MongoClient
from pymongo.collection import Collection
from pymongo.database import Database

from config.settings import settings

_mongo_client: Optional[MongoClient] = None
_client_lock = Lock()


def get_mongo_client() -> MongoClient:
    """获取全局 MongoClient（单例）"""
    global _mongo_client
    if _mongo_client is None:
        with _client_lock:
            if _mongo_client is None:
                client_kwargs = dict(
                    connectTimeoutMS=5000,
                    serverSelectionTimeoutMS=5000,
                    socketTimeoutMS=5000,
                    tz_aware=True,
                )
                if settings.MONGODB_USERNAME:
                    client_kwargs["username"] = settings.MONGODB_USERNAME
                    client_kwargs["password"] = settings.MONGODB_PASSWORD
                    client_kwargs["authSource"] = settings.MONGODB_AUTH_SOURCE
                _mongo_client = MongoClient(
                    settings.MONGODB_URI,
                    **client_kwargs,
                )
    return _mongo_client


def get_mongo_db() -> Database:
    """获取默认数据库"""
    client = get_mongo_client()
    return client[settings.MONGODB_DB]


def get_collection(name: str) -> Collection:
    """
    获取指定集合
    Args:
        name: 集合名称
    """
    return get_mongo_db()[name]

